// 封装 axios

import axios from "axios";
// import { Loading , Message } from 'element-ui';
import { message } from "antd";
import { HashHistory } from "../utils";

// const baseURL = "http://localhost:7000/"; // 本地开发
const baseURL = "http://101.37.167.214:7000/";

let loading = null;
export function showLoading(msg) {
  msg = msg || "请求中";
  message.loading(msg);
}

export function showSuccess(msg) {
  msg = msg || "success";
  message.destroy();
  message.success(msg);
}

export function showFail(msg) {
  msg = msg || "请求失败";
  message.destroy();
  message.error(msg);
}

axios.defaults.baseURL = baseURL; // 反向代理 冲突
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';   // 管理系统
axios.defaults.timeout = 60000; // 60S 超时

// 拦截器   Interceptors
// 请求发送之前的拦截器   Add a request interceptor
axios.interceptors.request.use(
  function (config) {
    var token = sessionStorage.token ? sessionStorage.token : "";
    if (token) {
      config.headers.token = token;
    }

    showLoading();

    return config;
  },
  function (error) {
    // Do something with request error
    showFail("请求失败");
    return Promise.reject(error);
  }
);

// 响应结束之后的拦截器  Add a response interceptor
axios.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    console.log(response);

    if (response.data.code == 200) {
      showSuccess(response.data.msg);
    } else {
      showFail(response.data.msg);
    }

    if (response.data.code == 403) {
      // router.replace({name:'login'})   // 阻止后退
      HashHistory.replace("/login");
    }

    return response;
  },
  function (error) {
    showFail("响应失败");
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  }
);

// POST  GET
export const get = (url, params, headers) => {
  return new Promise(function (resolve, reject) {
    axios
      .get(url, {
        params, // 参数
        headers, // 请求头
      })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

export const post = (url, body, headers) => {
  return new Promise(function (resolve, reject) {
    axios
      .post(url, body, {
        headers, // 请求头
      })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

export { baseURL, axios };
